package com.company.pushTools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.company.utils.AssertUtils;
import com.company.utils.Constant;
import com.company.utils.HttpClientUtils;
import com.company.utils.RedisUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("pushUtils")
public class PushUtils {
    private static final Logger LOGGER =LoggerFactory.getLogger(PushUtils.class);
    @Autowired
    PushBase pushBase;
    @Autowired
    private RedisUtils R;


    ThreadPoolManager threadPoolManager;
    public PushUtils() {
        threadPoolManager = ThreadPoolManager.newInstance();
    }

    /**
     * 推送
     * @param pushParams
     */
    public void pushByParams(PushParams pushParams) {
        LOGGER.info("推送入口参数------->",JSON.toJSON(pushParams));
        AssertUtils.isNull(pushParams,"没有找配置推送参数 -- >= "+pushParams);
        if (StringUtils.isNotEmpty(pushParams.getTouser())){
            pushParams.setCount(1);
//            sendToPool(pushParams);
            pushBase.initPush(pushParams);
        }else {
            List<String> openIdList = pushParams.getOpenIdList();
            pushParams.setCount(openIdList.size());
            for(String openId : openIdList){
                PushParams pushParams1 = new PushParams();
                BeanUtils.copyProperties(pushParams,pushParams1);
                pushParams1.setTouser(openId);
                pushBase.initPush(pushParams1);
            }
        }
    }




    /**
     * 扔到线程池
     * @param pushParams
     */
    public void sendToPool(PushParams pushParams){
        threadPoolManager.addExecuteTask(new Runnable() {
            PushParams pushParams2 = pushParams;
            @Override
            public void run() {
                try {
                    pushBase.initPush(pushParams2);
                } catch (Exception e){
                    AssertUtils.isFalse(false,"推送失败，请检查参数");
                }finally {
                    LOGGER.info("推送OK");
                }
            }
        });
    }

}
